<template>
  <div class="min-h-screen flex items-center justify-center bg-gradient-to-r from-blue-50 to-indigo-50">
    <a-card class="login-card shadow-2xl">
      <div class="text-center mb-6">
        <h2 class="text-3xl font-bold bg-gradient-to-r from-blue-600 to-indigo-600 bg-clip-text text-transparent">
          工厂设备管理系统
        </h2>
        <p class="mt-1 text-gray-500">请登录您的账号</p>
      </div>
      
      <a-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        class="mt-6 space-y-4"
        @submit="handleSubmit"
        :label-col-props="{ span: 0 }"
        :wrapper-col-props="{ span: 24 }"
      >
        <a-form-item field="username" :rules="[{ required: true, message: '请输入用户名' }]" hide-label>
          <a-input
            v-model="formData.username"
            placeholder="用户名"
            :disabled="loading"
            class="rounded-lg"
            :style="{ width: '100%' }"
          >
            <template #prefix>
              <icon-user class="text-blue-500" />
            </template>
          </a-input>
        </a-form-item>
        <a-form-item field="password" :rules="[{ required: true, message: '请输入密码' }]" hide-label>
          <a-input-password
            v-model="formData.password"
            placeholder="密码"
            :disabled="loading"
            class="rounded-lg"
          >
            <template #prefix>
              <icon-lock class="text-blue-500" />
            </template>
          </a-input-password>
        </a-form-item>
        <div class="flex justify-between items-center">
          <a-checkbox>记住我</a-checkbox>
          <a-link class="text-gray-500 hover:text-blue-500">忘记密码？</a-link>
        </div>
        <a-button
          type="primary"
          long
          :loading="loading"
          @click="handleSubmit"
          class="login-btn h-10 text-lg font-medium"
        >
          登录
        </a-button>
        <div class="mt-4 text-center">
          <span class="text-gray-500">还没有账号？</span>
          <router-link to="/register" class="text-blue-500 hover:text-blue-600 ml-1">
            立即注册
          </router-link>
        </div>
      </a-form>
    </a-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { Message } from '@arco-design/web-vue'
import type { FieldRule } from '@arco-design/web-vue'
import { userApi, UserInfo } from '@/api/user'
import { useStore } from '@/store'

const router = useRouter()
const store = useStore()

// 表单相关
const formRef = ref()
const loading = ref(false)
const showResetPasswordModal = ref(false)
const resetLoading = ref(false)
const resetFormRef = ref()
// 登录表单数据
const formData = reactive({
  username: '',
  password: '',
  userType: '工人',
  token: ''
})

// 表单验证规则
const rules = {
  username: [
    { required: true, message: '请输入用户名' }
  ],
  password: [
    { required: true, message: '请输入密码' },
    { minLength: 6, message: '密码长度不能小于6位' }
  ]
} as Record<string, FieldRule[]>

// 登录提交
const handleSubmit = async () => {
  try {
    await formRef.value?.validate()
    loading.value = true

    const res = await userApi.login(formData)
    console.log('登录响应:', res)

    if (res.code === 1 && res.data.token) {
      console.log('登录成功，保存token:', res.data.token)
      console.log('保存用户信息:', {
        userId: res.data.userId,
        username: res.data.userName,
        userType: res.data.userType,
        realName: res.data.name || ''
      })

      // 保存token和用户信息
      store.commit('SET_TOKEN', res.data.token)
      store.commit('SET_USER_INFO', {
        userId: res.data.userId,
        username: res.data.userName,
        userType: res.data.userType,
        realName: res.data.name || '',
        mobile: res.data.mobile || '',
        email: res.data.email || '',
        status: res.data.status || 1,
        createdAt: res.data.createdAt || new Date().toISOString(),
        updatedAt: res.data.updatedAt || new Date().toISOString(),
        lastLoginTime: res.data.lastLoginTime || new Date().toISOString()
      })

      // 登录成功后跳转
      console.log('准备跳转到:',  '/')
      router.push('/')
      Message.success('登录成功')
    } else {
      console.error('登录失败:', res.msg)
      Message.error(res.msg || '登录失败')
    }
  } catch (error) {
    console.error('登录错误:', error)
    if (error instanceof Error) {
      console.error('错误详情:', {
        name: error.name,
        message: error.message,
        stack: error.stack
      })
      Message.error(error.message)
    } else {
      Message.error('登录失败')
    }
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
.login-card {
  width: 500px;
  border-radius: 1rem;
  padding: 1.5rem;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
}

:deep(.arco-form-item) {
  margin-bottom: 12px;
}

:deep(.arco-input-wrapper) {
  border-radius: 0.5rem;
  height: 36px;
  transition: all 0.3s ease;
}

:deep(.arco-btn) {
  border-radius: 0.5rem;
  transition: all 0.3s ease;
}

.login-btn {
  background: linear-gradient(to right, #3b82f6, #4f46e5);
  border: none;
  height: 36px !important;
  font-size: 1rem !important;
}

.login-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(59, 130, 246, 0.3);
}

:deep(.arco-input-wrapper:focus-within) {
  border-color: #3b82f6;
  box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.1);
}
</style> 